<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="只允许为三级分类添加参数和属性" type="warning" show-icon :closable="false"></el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            clearable
            v-model="CascadeSeletIDArray"
            :options="CascaderData"
            :props="CascaderProp"
            @change="handleCascaderChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="商品参数" name="many">
          <el-button type="primary" :disabled="ButtonisDisable" @click="handleAddParamsDialog">添加参数</el-button>
          <el-table :data="manyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="handleTagRemove(scope.row,index)"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleEditParamsDialog(scope.row)"
                >编辑</el-button>

                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleParamsRemove(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="only">
          <el-button type="primary" :disabled="ButtonisDisable" @click="handleAddParamsDialog">添加属性</el-button>
          <el-table :data="onlyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="handleTagRemove(scope.row,index)"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleEditParamsDialog(scope.row)"
                >编辑</el-button>

                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleParamsRemove(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      @close="handleAddParamsDialogClose"
      :title="'添加'+DialogName"
      :visible.sync="AddParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="AddParamsFormData"
        :rules="AddParamsFormRules"
        ref="AddParamsFormRef"
        label-width="120px"
      >
        <el-form-item :label="DialogName+'名称'" prop="attr_name">
          <el-input v-model="AddParamsFormData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddParamsRequest">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      @close="handleEditParamsDialogClose"
      :title="'编辑'+DialogName"
      :visible.sync="EditParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="EditParamsFormData"
        :rules="EditParamsFormRules"
        ref="EditParamsFormRef"
        label-width="120px"
      >
        <el-form-item :label="DialogName+'名称'" prop="attr_name">
          <el-input v-model="EditParamsFormData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditParamsRequest">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      CascadeSeletIDArray: [],
      CascaderData: [],
      CascaderProp: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      AddParamsDialogVisible: false,
      AddParamsFormData: {
        attr_name: ""
      },
      AddParamsFormRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      },
      EditParamsDialogVisible: false,
      EditParamsFormData: {},
      EditParamsFormRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getCascaterData();
  },
  methods: {
    async getCascaterData() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.CascaderData = res.data;
    },
    handleCascaderChange() {
      if (this.CascadeSeletIDArray.length !== 3) {
        this.CascadeSeletIDArray = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      this.getTableData();
    },
    handleTabClick() {
      this.getTableData();
    },
    async getTableData() {
      const { data: res } = await this.$http.get(
        `categories/${this.ID}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(",")
          : [];
        element.inputVisible = false;
        element.inputValue = "";
      });

      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    handleAddParamsDialog() {
      this.AddParamsDialogVisible = true;
    },
    handleAddParamsRequest() {
      this.$refs.AddParamsFormRef.validate(async value => {
        if (!value) return;
        const { data: res } = await this.$http.post(
          `categories/${this.ID}/attributes`,
          {
            attr_name: this.AddParamsFormData.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error("操作失败");
        this.$message.success("添加成功");
        this.getTableData();
        this.AddParamsDialogVisible = false;
      });
    },
    handleAddParamsDialogClose() {
      this.$refs.AddParamsFormRef.resetFields();
    },
    async handleEditParamsDialog(row) {
      const { data: res } = await this.$http.get(
        `categories/${this.ID}/attributes/${row.attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.EditParamsFormData = res.data;

      this.EditParamsDialogVisible = true;
    },
    handleEditParamsDialogClose() {
      this.$refs.EditParamsFormRef.resetFields();
    },
    handleEditParamsRequest() {
      this.$refs.EditParamsFormRef.validate(async value => {
        if (!value) return;
        const { data: res } = await this.$http.put(
          `categories/${this.ID}/attributes/${this.EditParamsFormData.attr_id}`,
          {
            attr_name: this.EditParamsFormData.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) return this.$message.error("操作失败");
        this.$message.success("修改成功");
        this.getTableData();
        this.EditParamsDialogVisible = false;
      });
    },
    async handleParamsRemove(id) {
      try {
        const confirm = await this.$confirm("确认删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        if (confirm === "confirm") {
          const { data: res } = await this.$http.delete(
            `categories/${this.ID}/attributes/${id}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("操作失败");
          }
          this.$message.success("删除成功");
          this.getTableData();
        }
      } catch (error) {
        return this.$message.info("已取消删除");
      }
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        return;
      }
      row.attr_vals.push(row.inputValue);
      this.SaveTag(row);
      row.inputValue = "";

      row.inputVisible = false;
    },
    async SaveTag(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.ID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(",")
        }
      );
      if (res.meta.status !== 200) return this.$message.error("操作失败");
      this.$message.success("更新成功");
    },
    handleTagRemove(row, index) {
      row.attr_vals.splice(index, 1);
      this.SaveTag(row);
    }
  },
  computed: {
    ButtonisDisable() {
      if (this.CascadeSeletIDArray.length !== 3) {
        return true;
      }
      return false;
    },
    ID() {
      if (this.CascadeSeletIDArray.length === 3) {
        return this.CascadeSeletIDArray[2];
      } else {
        return null;
      }
    },
    DialogName() {
      if (this.activeName === "many") {
        return "商品参数";
      } else {
        return "商品属性";
      }
    }
  }
};
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-cascader {
  margin-left: 10px;
}
.el-row {
  margin-bottom: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>